package com.star.bookstore.product.exception;

import com.star.bookstore.common.excoption.CodeEnum;
import com.star.bookstore.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestControllerAdvice(basePackages = "com.star.bookstore.product.controller")
public class ProductExceptionControllerAdvice {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleVaildException(MethodArgumentNotValidException e){

        System.out.println("捕捉到异常");

        log.error("数据校验出现问题{},异常类型：{}" + e.getMessage(),e.getClass());
        BindingResult bindingResult = e.getBindingResult();
        Map<String, String> errorMap = new HashMap<>();
        bindingResult.getFieldErrors().forEach(fieldError -> {
            System.out.println(fieldError.getField() + "  " +fieldError.getDefaultMessage());
            errorMap.put(fieldError.getField(),fieldError.getDefaultMessage());
        });


        return R.error(CodeEnum.VAILD_EXCEPTION.getCode(),CodeEnum.VAILD_EXCEPTION.getMessage()).put("data",errorMap);
    }


/*
    @ExceptionHandler(value = Exception.class)
    public R handException(Exception e){
        log.error("数据校验出现问题{},异常类型：{}" + e.getMessage(),e.getClass());
        return R.error(CodeEnum.UNKNOW_EXCEPTION.getCode(),CodeEnum.UNKNOW_EXCEPTION.getMessage());
    }*/


}
